package com.wskj.library.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 胡洋
 * @describe  进行登录权限的验证
 * @Date 2018年3月22日下午6:14:53
 * @version 1.0
 */
@WebFilter(urlPatterns="/*",initParams=@WebInitParam(name="allowed",value="js,css,jpg,png,gif,bmp,xls,xlsx"))
public class LoginFilter implements Filter {
    List<String> allowed;
	
	@Override
	public void destroy() {
		

	}

	
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		
		//判读session中是否有值		
				HttpServletRequest request=(HttpServletRequest) req;
				HttpServletResponse response=(HttpServletResponse) resp;
				//用户 没有登录成功   
				Object name = request.getSession().getAttribute("user");		
				
				if(name==null) {			
					
					//判断请求的地址是否是  login.do  
					String uri = request.getRequestURI();					
					
					//截断  项目名
					String str = uri.substring(request.getContextPath().length());
					
					//后缀名  
					String ext = uri.substring(uri.lastIndexOf(".")+1);			
					//js  css  jpg  bmp  gif  png 					
					if("/admin/login.do".equalsIgnoreCase(str) || allowed.contains(ext) ||uri.contains("/yanzhenma.jpg")) {
						// 不拦截  登录地址 
					}else {
					  response.sendRedirect(request.getContextPath()+"/admin/login.do");
					  return;				
					}
				}
				
				chain.doFilter(request, response);
	}

	
	
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		String allow = config.getInitParameter("allowed");
		allowed=Arrays.asList(allow.split(","));
	}

}
